import React from 'react';
import { connect } from 'react-redux';
import { Menu, Icon, message } from 'antd';
import * as routerActions from 'react-router-redux';
import { generateUUID } from 'Utils/index';
import Api from 'Utils/api';
import moment from 'moment';
import './index.scss';

class Organize extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      openKeys: ['11'],
      value: '',
      Treevalue: undefined,
      organiseData: props.organiseData || [],
      selectData: {},
      checkRecord: [],
      selectedKeys: ['all']
    };
    this.renderRecord = ::this.renderRecord;
    this.initRecord = ::this.initRecord;
    this.initData = ::this.initData;
    this.initData();
  }
  initData() {
    const api = new Api({
      method: 'GET',
      path: '/depts/level',
      success: (res) => {
        this.props.initData(res);
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  componentWillReceiveProps(nextProp) {
    this.setState({
      selectData: nextProp.selectData
    }, () => {
      if (this.state.selectData.id) {
        this.initRecord(this.state.selectData.id);
      }
    });
  }
  initRecord(id) {
    const api = new Api({
      method: 'GET',
      path: `/depts/checks/${id}`,
      query: {
        offset: 0,
        limit: 7
      },
      success: (res) => {
        this.setState({
          checkRecord: res.data_list
        });
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  onMenuClick(e) {
    this.setState({
      openKeys: e,
    });
  }
  handleMenuItemClick(e) {
    if (e.key === 'all') {
      this.initData();
      this.setState({
        selectData: {},
        selectedKeys: [e.key]
      });
      return;
    }
    // get detail
    const api = new Api({
      method: 'GET',
      path: `/depts/level/${e.key}`,
      success: (res) => {
        this.setState({
          selectData: res,
          selectedKeys: [e.key]
        });
        if (res.id) {
          this.props.reload(res);
        }
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
    //get rcord
    this.initRecord(e.key);
  }
  renderMenu() {
    const { organiseData, selectedKeys } = this.state;
    return (
      <div>
        <Menu
          onOpenChange={this.onMenuClick.bind(this)}
          onClick={this.handleMenuItemClick.bind(this)}
          mode="inline"
          selectedKeys={selectedKeys}
        >
          <Menu.Item key="all">
            <span className="sub-label">全县</span>
          </Menu.Item>
          {
            organiseData.map((item) => {
              return this.renderMenuItem(item);
            })
          }
        </Menu>
      </div>
    );
  }
  renderMenuItem(Pitem) {
    const { openKeys } = this.state;
    if (!Pitem.sub_depts || Pitem.sub_depts.length === 0) {
      return (
        <Menu.Item key={Pitem.id}>
          <span className="sub-label">{Pitem.name}</span>
        </Menu.Item>
      );
    }
    return (
      <Menu.SubMenu
        key={Pitem.id}
        title={
          <span className="label">
            <Icon type={openKeys.indexOf(Pitem.key) > -1 ? 'caret-down' : 'caret-right'} />
            {Pitem.name}
          </span>
        }
        onTitleClick={this.handleMenuItemClick.bind(this)}
      >
        {
          Pitem.sub_depts.map((item) => {
            return this.renderMenuItem(item);
          })
        }
      </Menu.SubMenu>
    );
  }
  renderRecord() {
    const { checkRecord } = this.state;
    const nodeInfo = [];
    for (let i = 0, len = checkRecord.length; i < len; i++) {
      nodeInfo.push((
        <div className="record" key={generateUUID()}>
          <span>
            {checkRecord[i].check_date ? moment(checkRecord[i].check_date).format('YYYY/MM/DD') : ''}
            检查{checkRecord[i].name || ''}
          </span>
          <span className="result">{checkRecord[i].result_msg || ''}</span>
        </div>
      ));
    }
    return nodeInfo;
  }
  render() {
    const { selectData, checkRecord } = this.state;
    return (
      <div className="business">
        <div>
          <div className="select">
            <div className="menu">
              {
                this.renderMenu()
              }
            </div>
          </div>
        </div>
        <div className="record-wrap organize-margin">
          <div onClick={() => { this.props.dispatch(routerActions.push(`/system/bigdata/map/records/reculatory_agency/${selectData.id}`)); }} className="title">
            检查记录 <div className="title-more">{checkRecord.length > 0 ? '更多》' : ''}</div>
          </div>
          <div className="content organize-height">
            {
              this.renderRecord()
            }
          </div>
          {
            <div className="info">
              <div className="item">机构名称：{selectData ? selectData.name : ''}</div>
              <div className="item">地址：{selectData ? selectData.address : ''}</div>
              <div className="item">联系电话：{selectData ? selectData.phone : ''}</div>
              <div className="item">领导：{selectData ? selectData.leader : ''}</div>
            </div>
          }
        </div>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    ...state.routing,
  };
}

export default connect(mapStateToProps)(Organize);
